package com.chart.web.controller.chart.sta;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.chart.chart.domian.ChartConfigs;
import com.chart.chart.domian.dto.ChartDateTto;
import com.chart.chart.domian.vo.ChartSmartVo;
import com.chart.chart.service.IChartConfigsService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.utils.ChartDataUtils;
import com.chart.common.utils.ExcelDataUtils;
import com.chart.common.utils.ExcelUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 地图
 *
 * @author chart
 */
@RestController
@RequestMapping("/map/chart")
public class MapChartController extends BaseController {

    @Autowired
    private IChartConfigsService chartConfigsService;

    //杭州市xx信息区域分布示意图
    @PostMapping("/regionalDistribution/importData")
    public AjaxResult importData(@RequestBody ChartDateTto chartDateTto) throws Exception {
        String chartValue = chartDateTto.getChartValue();
        List<List<String>> lists = ChartDataUtils.extractDataFromList(chartDateTto.getDataList());
        if (chartDateTto.getConfigId() == 40) {

            // 将数据列表转换为 Sheet
            Sheet sheet = ExcelDataUtils.convertDataListToSheetsa(chartDateTto.getDataList());

            // 获取数据
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            if (ObjectUtils.isEmpty(getdata.get(0).get(1))) {
                return AjaxResult.error("请填充最小值数据");
            }
            if (ObjectUtils.isEmpty(getdata.get(1).get(1))) {
                return AjaxResult.error("请填充最大值数据");
            }

            String minV = getdata.get(0).get(1);
            String maxV = getdata.get(1).get(1);
            String infoV = getdata.get(2).get(1);

            List<JSONObject> maps = new ArrayList<>();
            for (int i = 4; i < getdata.size(); i++) {
                List<String> strings = getdata.get(i);
                if (!CollectionUtils.isEmpty(strings)) {
                    JSONObject map = new JSONObject();
                    for (int i1 = 0; i1 < strings.size(); i1++) {
                        String s = strings.get(i1);
                        if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                            if (i1 == 0) {
                                map.put("name", s);
                            } else {
                                map.put("value", s);
                            }
                        }
                    }
                    maps.add(map);
                }
            }

            // 获取 chartValue 并解析为 JSONObject
            System.out.println("chartValue: " + chartDateTto.getChartValue()); // 调试打印
            JSONObject jsonObject = JSON.parseObject(chartDateTto.getChartValue());

            // 获取系列数据
            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject jsonObject1 = series.get(0);
            jsonObject1.put("name", infoV);
            jsonObject1.put("data", maps);

            // 处理 visualMap
            JSONArray visualMapArray = jsonObject.getJSONArray("visualMap");
            if (visualMapArray != null && !visualMapArray.isEmpty()) {
                for (int i = 0; i < visualMapArray.size(); i++) {
                    JSONObject visualMapObject = visualMapArray.getJSONObject(i);
                    visualMapObject.put("min", Double.parseDouble(minV));
                    visualMapObject.put("max", Double.parseDouble(maxV));
                }
            } else {
                return AjaxResult.error("visualMap 数据为空或格式不正确");
            }

            // 更新系列数据和 visualMap
            jsonObject.put("series", jsonObject1);
            jsonObject.put("visualMap", visualMapArray);

            ArrayList<ChartSmartVo> chartSmartVoArrayList = new ArrayList<>();
            ChartSmartVo chartSmartVo = new ChartSmartVo();
            chartSmartVo.setConfigValue(JSON.toJSONString(jsonObject));
            chartSmartVoArrayList.add(chartSmartVo);
            System.out.println(JSON.toJSONString(jsonObject));
            return AjaxResult.success(chartSmartVoArrayList);

          /*  Sheet sheet = ExcelDataUtils.convertDataListToSheetsa(chartDateTto.getDataList());

            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            if (ObjectUtils.isEmpty(getdata.get(0).get(1))) {
                return AjaxResult.error("请填充最小值数据");
            }
            if (ObjectUtils.isEmpty(getdata.get(1).get(1))) {
                return AjaxResult.error("请填充最大值数据");
            }

            String minV = getdata.get(0).get(1);
            String maxV = getdata.get(1).get(1);
            String infoV = getdata.get(2).get(1);


            List<JSONObject> maps = new ArrayList<>();
            for (int i = 4; i < getdata.size(); i++) {
                List<String> strings = getdata.get(i);
                if (!CollectionUtils.isEmpty(strings)) {
                    JSONObject map = new JSONObject();
                    for (int i1 = 0; i1 < strings.size(); i1++) {
                        String s = strings.get(i1);
                        if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                            if (i1 == 0) {
                                map.put("name", s);
                            } else {
                                map.put("value", s);
                            }
                        }
                    }
                    maps.add(map);
                }
            }

          //  ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(chartValue);

            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject jsonObject1 = series.get(0);
            jsonObject1.put("name", infoV);
            jsonObject1.put("data", maps);

            String minMaxAxis = JSON.toJSONString(jsonObject.get("visualMap"));
            JSONObject jsonObjectMinMAx = JSON.parseObject(minMaxAxis);
            jsonObjectMinMAx.put("min", Double.parseDouble(minV));
            jsonObjectMinMAx.put("max", Double.parseDouble(maxV));
            jsonObject.put("visualMap", jsonObjectMinMAx);


            jsonObject.put("series", jsonObject1);
            return AjaxResult.success(JSON.toJSONString(jsonObject));*/

        }


        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode chartValueJson = objectMapper.readTree(chartValue);

        // 获取dataset节点
        ArrayNode dataset = (ArrayNode) chartValueJson.path("dataset");
        // 更新dataset中的source节点
        dataset = ChartDataUtils.updateDatasetSources(dataset, lists, objectMapper);

        // 移除集合中第一个对象的第一个元素
        if (!lists.isEmpty() && !lists.get(0).isEmpty()) {
            lists.get(0).remove(0);
        }

        // 获取series字段并删除其余对象
        ArrayNode seriesArray = (ArrayNode) chartValueJson.path("series");
        if (seriesArray.size() > 1) {
            while (seriesArray.size() > 1) {
                seriesArray.remove(1);
            }
        }

        // 计算第一个对象剩余元素数量
        int firstObjectRemainingElements = lists.isEmpty() ? 0 : lists.get(0).size();

        // 复制series的第一个对象
        JsonNode firstSeriesObject = seriesArray.get(0);
        for (int i = 1; i < firstObjectRemainingElements; i++) {
            seriesArray.add(firstSeriesObject.deepCopy());
        }

        // 在这里添加新的逻辑来处理 datasetIndex 字段
        for (int i = 0; i < seriesArray.size(); i++) {
            ObjectNode seriesObject = (ObjectNode) seriesArray.get(i);
            if (seriesObject.has("datasetIndex")) {
                seriesObject.put("datasetIndex", i);
            } else {
                seriesObject.put("datasetIndex", i);
            }
        }

        // 获取legend节点并更新data
        JsonNode legend = chartValueJson.path("legend");
        ChartDataUtils.updateLegendData(legend, lists);

        // 更新series中每个对象的name字段
        for (int i = 0; i < firstObjectRemainingElements; i++) {
            ((ObjectNode) seriesArray.get(i)).put("name", lists.get(0).get(i));
        }

        String updatedChartValue = chartValueJson.toString();

        ArrayList<ChartSmartVo> newList = new ArrayList<>();
        // 获取ChartConfigs对象
        ChartConfigs configs = chartConfigsService.getById(chartDateTto.getConfigId());
        // 创建新的ChartSmartVo对象并设置属性
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigId(configs.getId()); // 假设ChartConfigs有getId方法
        chartSmartVo.setConfigName(configs.getConfigName()); // 假设ChartConfigs有getName方法
        chartSmartVo.setConfigValue(updatedChartValue);
        chartSmartVo.setChartTypeId(configs.getChartTypeId());

        newList.add(chartSmartVo);
        System.out.println(updatedChartValue);
        return AjaxResult.success(newList);
    }


/*

    //杭州市xx信息区域分布示意图
    @PostMapping("/regionalDistribution/importData")
    public AjaxResult importData(MultipartFile file,Long configId) throws Exception {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            if (ObjectUtils.isEmpty(getdata.get(0).get(1))) {
                return AjaxResult.error("请填充最小值数据");
            }
            if (ObjectUtils.isEmpty(getdata.get(1).get(1))) {
                return AjaxResult.error("请填充最大值数据");
            }

            String minV = getdata.get(0).get(1);
            String maxV = getdata.get(1).get(1);
            String infoV = getdata.get(2).get(1);


            List<JSONObject> maps = new ArrayList<>();
            for (int i = 4; i < getdata.size(); i++) {
                List<String> strings = getdata.get(i);
                if (!CollectionUtils.isEmpty(strings)) {
                    JSONObject map = new JSONObject();
                    for (int i1 = 0; i1 < strings.size(); i1++) {
                        String s = strings.get(i1);
                        if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                            if (i1 == 0) {
                                map.put("name", s);
                            } else {
                                map.put("value", s);
                            }
                        }
                    }
                    maps.add(map);
                }
            }

            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject jsonObject1 = series.get(0);
            jsonObject1.put("name", infoV);
            jsonObject1.put("data", maps);

            String minMaxAxis = JSON.toJSONString(jsonObject.get("visualMap"));
            JSONObject jsonObjectMinMAx = JSON.parseObject(minMaxAxis);
            jsonObjectMinMAx.put("min", Double.parseDouble(minV));
            jsonObjectMinMAx.put("max", Double.parseDouble(maxV));
            jsonObject.put("visualMap", jsonObjectMinMAx);


            jsonObject.put("series", jsonObject1);
            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally {
            workbook.close();
        }
    }
*/

    //杭州市xx信息区域分布示意图
    @PostMapping("/regionalDistribution/v2/importData")
    public AjaxResult v2importData(@RequestBody List<Map<String, Object>> dataLists
            , Long configId) throws Exception {
        XSSFWorkbook workbook = null;
        try {
       /*     workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);*/
            Sheet sheet = ExcelUtils.convertDataListToSheetRemoveNineAndOne(dataLists);

            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            if (ObjectUtils.isEmpty(getdata.get(0).get(1))) {
                return AjaxResult.error("请填充最小值数据");
            }
            if (ObjectUtils.isEmpty(getdata.get(1).get(1))) {
                return AjaxResult.error("请填充最大值数据");
            }

            String minV = getdata.get(0).get(1);
            String maxV = getdata.get(1).get(1);
            String infoV = getdata.get(2).get(1);


            List<JSONObject> maps = new ArrayList<>();
            for (int i = 4; i < getdata.size(); i++) {
                List<String> strings = getdata.get(i);
                if (!CollectionUtils.isEmpty(strings)) {
                    JSONObject map = new JSONObject();
                    for (int i1 = 0; i1 < strings.size(); i1++) {
                        String s = strings.get(i1);
                        if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                            if (i1 == 0) {
                                map.put("name", s);
                            } else {
                                map.put("value", s);
                            }
                        }
                    }
                    maps.add(map);
                }
            }

            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());

            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            JSONObject jsonObject1 = series.get(0);
            jsonObject1.put("name", infoV);
            jsonObject1.put("data", maps);

            String minMaxAxis = JSON.toJSONString(jsonObject.get("visualMap"));
            JSONObject jsonObjectMinMAx = JSON.parseObject(minMaxAxis);
            jsonObjectMinMAx.put("min", Double.parseDouble(minV));
            jsonObjectMinMAx.put("max", Double.parseDouble(maxV));
            jsonObject.put("visualMap", jsonObjectMinMAx);


            jsonObject.put("series", jsonObject1);
            return AjaxResult.success(JSON.toJSONString(jsonObject));
        } finally {
            workbook.close();
        }
    }
}
